package dao

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"todo-list/config"
)

var _db *gorm.DB

func InitMySQL() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True", config.DBUser, config.DBPassword, config.DBHost, config.DBPort, config.DBName)
	var ormLogger logger.Interface
	if gin.Mode() == gin.DebugMode {
		ormLogger = logger.Default.LogMode(logger.Info)
	} else {
		ormLogger = logger.Default
	}
	ms, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: ormLogger})
	if err != nil {
		logrus.Fatalf("open database fail: %s", err.Error())
	}
	_db = ms
	migration()
}

func NewDBClient(ctx context.Context) *gorm.DB {
	newDB := _db
	return newDB.WithContext(ctx)
}
